package com.example.tangjiangxu.threedslidinglayoutdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * Created by tangjiangxu on 4/6/17.
 * 生成镜像图片，完成三维操作
 */
public class Image3dView extends View{
    private static final String TAG = "Image3dView";

    /** 源视图，用于生成图片对象 **/
    private View sourceView;
    /** 根据传入的源视图生成的图片对象 **/
    private Bitmap sourceBitmap;
    /** 源视图的宽度 **/
    private float sourceWidth;
    /** 用于对图片进行矩阵操作 **/
    private Matrix matrix = new Matrix();
    /** 用于对图片进行三维操作 **/
    private Camera camera = new Camera();

    public Image3dView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 提供外部接口，允许向Image3dView传入源视图
     * @param view
     */
    public void setSourceView(View view) {
        sourceView = view;
        sourceWidth = sourceView.getWidth();
    }

    public void clearSourceBitmap() {
        if (sourceBitmap != null) {
            sourceBitmap = null;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.e(TAG, "onDraw: " );
        try {
            super.onDraw(canvas);
            if (sourceBitmap == null) {
                getSourceBitmap();
            }
            //计算图片需要旋转对角度
            float degree = 90 - (90 / sourceWidth) * getWidth();
            camera.save();
            camera.rotateY(degree);
            camera.getMatrix(matrix);
            camera.restore();
            //将旋转对中心点移动到屏幕左边缘到中间位置
            matrix.preTranslate(0, -getHeight() / 2);
            matrix.postTranslate(0, getHeight() / 2);
            canvas.drawBitmap(sourceBitmap, matrix, null);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取源视图对应对图片对象
     */
    private void getSourceBitmap() {
        Log.e(TAG, "getSourceBitmap: ");
        if (sourceView != null) {
            sourceView.setDrawingCacheEnabled(true);
            sourceView.layout(0, 0, sourceView.getWidth(), sourceView.getHeight());
            sourceView.buildDrawingCache();
            sourceBitmap = sourceView.getDrawingCache();
        }
    }

}
